package com.ld.security.auth.shiro.advice;

import cn.hutool.core.lang.Console;
import com.ld.security.auth.shiro.anno.AesKey;
import com.ld.security.auth.shiro.config.ShiroProperties;
import com.ld.security.common.core.util.AesCrypt;
import com.ld.security.common.core.util.JsonUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;


/**
 * 请求响应处理类<br>
 *
 * 对加了@Encrypt的方法的数据进行加密操作
 */
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    ShiroProperties shiroProperties;

    private Logger logger = LoggerFactory.getLogger(EncryptResponseBodyAdvice.class);


    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {



        Method method =  returnType.getMethod();

        AesKey aesKey =      returnType.getAnnotatedElement().getAnnotation(AesKey.class);

        for (Annotation annotation : method.getAnnotations()) {
      Console.log(annotation);
    }

        if(aesKey == null){
            if(!shiroProperties.isOpenAes()){
                return body;
            }

        }else if(!aesKey.encode()){
            return body;
        }

        String content = JsonUtil.toJson(body);
        String text = AesCrypt.encrypt(content);
        return text;
    }



    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // TODO Auto-generated method stub


        return true;
    }

}